# -*- coding: utf-8 -*-
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt


#生成训练数据
x_train = np.linspace(0, 12, 40)
y_train = np.linspace(0, 5, 40)
#加噪声
y_train += np.random.randn(40) * 0.5
plt.scatter(x_train, y_train)

#定义Tensorflow参数:x,y,w,b
X = tf.placeholder(dtype=tf.float32, shape=[None,1], name="data")
Y = tf.placeholder(dtype=tf.float32, shape=[None,1], name="target")

#定义两个变量W和b
W = tf.Variable(np.random.randn(1, 1), name="weight", dtype=tf.float32)
b = tf.Variable(np.random.randn(1, 1), name="bias", dtype=tf.float32)

#创建线性模型
pred = tf.matmul(X, W) + b

#损失函数（均方误差）
#H = sum[0-m](y - yi) ^ 2
#reduce_sum降维加法，(pred-Y)相同位置相减，m=40个点
cost = tf.reduce_sum(tf.pow(tf.subtract(pred, Y), 2)) / 40
#cost = tf.reduce_mean(tf.pow(tf.substract(pred, Y), 2))

#创建剃度下降优化器
optimizer = tf.train.GradientDescentOptimizer(0.01).minimize(cost)


#开始运算
#训练次数
epoches = 1000
with tf.Session() as sess:
    #变量初始化
    sess.run(tf.global_variables_initializer())
    #循环
    for i in range(epoches):
        #给占位符设置数据，并开始训练
        opt, c = sess.run([optimizer, cost], feed_dict={X:x_train.reshape(-1,1), Y:y_train.reshape(-2,1)})
        #打印
        if (i+1) % 100 == 0:
            w_ = sess.run(W)
            b_ = sess.run(b)
            print("训练 %d 次，损失 %0.4f， 斜率: %0.2f, 截距: %0.2f" % (i, c, w_, b_))
    c = sess.run(cost, feed_dict={X:x_train.reshape(-1,1), Y:y_train.reshape(-2, 1)})
    w_ = sess.run(W)
    b_ = sess.run(b)
    print("训练结束，斜率: %0.2f, 截距: %0.2f" % ( w_, b_))

#绘制回归线
x1 = np.linspace(0, 12, 200)
plt.plot(x1, x1 * 0.42 + 0.15, color="green", label="slope: %0.2f, intercept: %0.2f" % ( w_, b_))
plt.legend()
plt.show()
